var path = require('path');
var config = require('./config');
var routeMvc;
module.exports = function (app) {
    app.all('*', function(req, res, next){
        console.log('session:', req.session);
        app.locals.session = req.session;
        next();
    });
    //错误处理.//这个处理要放在正则匹配处理的前面
    app.use('/error/:errorCode', function(req, res){
        res.status(req.params.errorCode).render('error', {errorType: req.params.errorCode, layout: false});
    });
    //后台需验证登陆之类 。//这个处理要放在正则匹配处理的前面
    app.all('/admin/*', function (req, res, next) {
        if(!req.session.user){
            res.status(403).render('public/jump', {layout: false, title: '跳转', jumpInfo: '无权操作,请登录!', jumpUrl: '/page/login'});
        }else{
            next();
        }

    });

    //
    app.all(['/', '/:module'], function (req, res) {
        return routeMvc(req, res, req.params.module);
    });
    app.all('/:module/:method', function (req, res) {
        return routeMvc(req, res, req.params.module, req.params.method);
    });
    app.all('/:module/:method/:id', function (req, res) {
        return routeMvc(req, res, req.params.module, req.params.method, req.params.id);
    });

    //这个请求放到最后，如果上面的处理都没有进入则，为404
    app.use(function(req, res){
        res.status(404).render('error', {type: 404});
    });
};

routeMvc = function (req, res, module, methodName, id) {
    if(config.err){
        //res.end(config.err.message);

        res.redirect('/error/500');
        console.log(config.err);
        return;
    }
    module = module || 'index';
    try {
        var controller = require('./controller/' + module);
    } catch (e) {
        res.redirect('/error/404');
    }
    methodName = methodName || 'index';

    if (methodName in controller) {
        controller[methodName](req, res, id);
    } else {
        res.redirect('/error/404');
    }


}